package com.ruoyi.system.utils;

import redis.clients.jedis.Jedis;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LuaUtils {

    /**
     * 脚本调用
     * @param uid 用户唯一标识
     */
    public static String LuaCall(Integer uid) {
        Jedis jedis = null;
        try {
            jedis = new Jedis("localhost"); // 在实际应用中，应从配置中获取此值

            String joinKey = "join_key";
            String stockKey = "stock_key";

            String uidStr = uid.toString(); // 避免重复转换

            // Lua 脚本，确保减少库存和添加用户到集合是原子性的
            String luaScript = " -- 参与秒杀的用户集合\n" +
                    "local join_key = KEYS[1]\n" +
                    "local stock_key = KEYS[2]\n" +
                    "local uid = ARGV[1]\n" +
                    "local has_buy = redis.call(\"sismember\", join_key, uid)\n" +
                    "if has_buy == 0 then\n" +
                    "  local stock = redis.call(\"decrby\", stock_key, 1)\n" + // 推荐使用decrby，明确减去1
                    "  if stock >= 0 then\n" +
                    "    redis.call(\"sadd\", join_key, uid)\n" +
                    "    return 1\n" + // 返回1表示可以参加秒杀，后续进行订单处理
                    "  else\n" +
                    "    return -1\n" + // 返回-1表示因为没有库存不能参加秒杀
                    "  end\n" +
                    "else\n" +
                    "  return -3\n" + // 返回-3表示已经参与过活动
                    "end\n";

            List<String> keys = Arrays.asList(stockKey, joinKey); // 注意keys的顺序应与Lua脚本中KEYS的顺序一致
            List<String> argv = Collections.singletonList(uidStr);
            Long result = (Long) jedis.eval(luaScript, keys, argv);

            if (result == 1) {
                System.out.println("恭喜您，秒杀成功！");
                return "秒杀成功";
            } else if (result == -1) {
                System.out.println("秒杀失败，商品已售罄。");
                return "秒杀失败，商品已售罄";
            } else if (result == -3) {
                System.out.println("您已经参与过该活动。");
                return "已参与过活动";
            } else {
                // 如果Lua脚本返回了其他值（理论上不应该发生），可以抛出异常或返回错误消息
                throw new IllegalStateException("Unexpected Lua script return value: " + result);
            }
        } catch (Exception e) {
            e.printStackTrace(); // 在实际应用中，应进行更详细的错误处理
            return "操作出错";
        } finally {
            if (jedis != null) {
                jedis.close(); // 确保Jedis连接被正确关闭
            }
        }
    }
}
